package apis

import (
	"QImages/database"
	"QImages/entity"
	"QImages/serializer"
	"log"
	"net/http"

	"github.com/gin-gonic/gin"
)

type ParamCollect struct {
	UserID  uint `json:"userId" binding:"required"`
	ImageID uint `json:"imageId" binding:"required"`
}

//Collect 执行收藏操作
func Collect(c *gin.Context) {
	var param ParamCollect
	err := c.ShouldBindJSON(&param)
	if err != nil {
		log.Println(err)
		c.JSON(http.StatusOK, serializer.ParamErr("", err))
		return
	}
	collection := entity.Collection{
		UserID:  param.UserID,
		ImageID: param.ImageID,
	}
	id, err := collection.Insert()
	if err != nil {
		log.Println(err)
		c.JSON(http.StatusOK, serializer.DBErr("收藏失败", err))
		return
	}
	c.JSON(http.StatusOK, serializer.OK("图片收藏成功", id))
}

//CancelCollect 取消收藏
func CancelCollect(c *gin.Context) {
	userId := c.Query("userId")
	imageId := c.Query("imageId")
	if userId == "" || imageId == "" {
		c.JSON(http.StatusOK, serializer.ParamErr("参数不完整", nil))
		return
	}
	if err := database.DB.Where("user_id = ? and image_id = ?", userId, imageId).Delete(entity.Collection{}).Error; err != nil {
		log.Println(err)
		c.JSON(http.StatusOK, serializer.DBErr("取消收藏失败", err))
		return
	}
	c.JSON(http.StatusOK, serializer.OK("取消收藏成功", nil))
}

// GetCollections 根据id查找收藏
func GetCollections(c *gin.Context) {
	uid := c.Query("uid")
	if uid == "" {
		c.JSON(http.StatusOK, serializer.ParamErr("参数不完整", nil))
		return
	}
	var cs []entity.Collection
	if err := database.DB.Where("user_id = ?", uid).Find(&cs).Error; err != nil {
		log.Println(err)
		c.JSON(http.StatusOK, serializer.DBErr("", err))
		return
	}
	c.JSON(http.StatusOK, serializer.OK("查询成功", serializer.BuildCollections(cs)))
}
